package com.pubinfo.passbook.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import com.pubinfo.passbook.common.model.vo.base.ResultCode;
import com.pubinfo.passbook.common.utils.SessionCookieUtils;
import com.pubinfo.passbook.shiro.token.JwtToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
public class MyPassThruAuthenticationFilter extends PassThruAuthenticationFilter {
  
  //获取请求方法，若为OPTIONS请求直接返回True放行
  @Override
  public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
    
    HttpServletRequest req = (HttpServletRequest) request;
    if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
      return true;
    }
    return super.onPreHandle(request, response, mappedValue);
  }
  
  @Override
  protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    HttpServletResponse httpResp = WebUtils.toHttp(response);
    HttpServletRequest httpReq = WebUtils.toHttp(request);
    
    /** 系统重定向会默认把请求头清空，这里通过拦截器重新设置请求头，解决跨域问题 */
    httpResp.addHeader("Access-Control-Allow-Origin", httpReq.getHeader("Origin"));
    httpResp.addHeader("Access-Control-Allow-Headers", "*");
    httpResp.addHeader("Access-Control-Allow-Methods", "*");
    httpResp.addHeader("Access-Control-Allow-Credentials", "true");
    //客户端的cookie中的ticket判断是否已经登录过的
    String ticketToken = SessionCookieUtils.getCookie(httpReq, "token");
    if (StringUtils.isBlank(ticketToken)) {
      ticketToken = httpReq.getHeader("token");
    }
  
    if (isLoginRequest(request, response)) {
      return true;
    } else if (StringUtils.isNotBlank(ticketToken)) {
      try {
        //校验ticketToken的有效性
        JwtToken jwtToken = new JwtToken(ticketToken);
        //提交给realm进行登录
        getSubject(request, response).login(jwtToken);
        //如果没有
      } catch (Exception e) {
        log.info("token验证失败");
        //  httpServletResponse.sendRedirect("/loginHtml");
      }
      return true;
    } else {
      httpResp.setContentType("application/json; charset=utf-8");
      
      PrintWriter out = httpResp.getWriter();
      httpResp.setCharacterEncoding("utf-8");
      // 返回自己的json
      out.write(JSON.toJSONString(JsonResult.error(ResultCode.UNAUTHORIZED)));
      out.flush();
      out.close();
      return false;
//      saveRequestAndRedirectToLogin(request, response);
//      return false;
    }
  }
}
